package com.ithinks.flow.common.utils.protocol.netty.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Description
 * @ClassName EchoClient
 * @Author MR.LI
 * @date 2020.12.09 10:36
 */
public class EchoClient {

    private String host;

    private int port;


    public EchoClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            //客户端启动
            bootstrap.group(group)
                    //指明使用NIO进行网络通讯
                    .channel(NioSocketChannel.class)
                    //配置远程服务器的地址
                    .remoteAddress(new InetSocketAddress(host,port))
                    //绑定处理器
                    .handler(new EchoClientHandler());
            //连接到远程节点，阻塞等待直到连接完成
            ChannelFuture future = bootstrap.connect().sync();
            //阻塞，直到channel关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        EchoClient echoClient = new EchoClient("127.0.0.1",8888);
        echoClient.start();
    }


}
